package starter;

import java.util.HashMap;

import org.omg.PortableServer.POA;
import euclid.*;
import gcdProcess.gcdProcessImpl;

/**
 * Implementation of the methods of the starter
 *
 */
public class StarterImpl extends StarterPOA {
	private POA poa;
	private String name;
	private Coordinator coordinator;
	private static HashMap<Integer, gcdProcess> listProcess;
	
	/**
	 * Construction of the starter
	 * @param name of the starter
	 * @param poa
	 * @param coordinator (reference of the current coordinator)
	 */
	public StarterImpl(String name, POA poa, Coordinator coordinator){
		this.name = name;
		this.poa = poa;
		this.coordinator = coordinator;
	}
	
	@Override
	public String getName() {
		return name;
	}

	@Override
	public void startProcess(int number) {
		//number = number of process to start
		listProcess = new HashMap<Integer,gcdProcess>();
		for(int i=0; i<number; i++)
		{
			try {
				//create a new process
				gcdProcessImpl newProcess = new gcdProcessImpl(name, i,coordinator);
				System.out.println("Process " + newProcess.getProcessId() + " is started");
				gcdProcess ProcessRef = gcdProcessHelper.narrow(poa.servant_to_reference(newProcess));
				listProcess.put(i,ProcessRef);
				//log the process to the coordinator
				coordinator.logProcess(name, i);
			} catch (Exception e) {
				System.err.println("Problem when creation the process");
				e.printStackTrace();
			}
		}
		
	}

	@Override
	public gcdProcess getProcess(int id) {
		return listProcess.get(id);
	}

	@Override
	public void endStarter() {
		if(listProcess!=null)
		{
			for(gcdProcess p: listProcess.values())
			{
				p.endProcess();
			}
			listProcess = null;
		}
		System.out.println("The Starter " + name + " is finished");
		
	}

}
